//路由鉴权：路由组件访问权限的设置
import router from "./router";
//引入nprogress进度条
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import setting from "./setting";
//去除加载时候的⭕️圈圈
nprogress.configure({ showSpinner: false });
//引入用户仓库
import useUserStore from "./store/modules/user";
//引入Pinia仓库
import pinia from "@/store";
//应用仓库
let userStore = useUserStore(pinia);
//全局守卫：项目中任意路由切换都会触发的钩子
// 全局前置守卫:访问路由之前
router.beforeEach(async (to: any, from: any, next: any) => {
  // to:想要访问的路由;from:从哪个路由而来;next:路由放行
  //   console.log(to);
  //动态更新项目标题
  document.title = `${setting.title}-${to.meta.title}`;
  nprogress.start();
  //获取token
  let token = userStore.token;
  //用户登录判断
  if (token) {
    //有token时不能访问登录页面 如果访问登录页面直接跳转到home页面
    if (to.path == "/login") {
      next({ path: "/" });
    } else {
      try {
        //获取用户信息
        await userStore.userInfo();
        next();
      } catch (error) {
        //token过期｜手动更改本地存储token
        //退出登录 清空用户信息->跳转到登录页面
        await userStore.userLayout();
        next({ path: "/login", redirect: to.path });
      }
    }
  } else {
    //去往登录页面时候放行
    if (to.path == "/login") {
      next();
    } else {
      //没有token时去访问登录页面
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});
//全局后置守卫：访问路由之后
router.afterEach((to: any, from: any) => {
  nprogress.done();
});
